package cn.fy.sqlite.dao;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.widget.Toast;

import java.util.ArrayList;

import cn.fy.sqlite.db.SQLite;
import cn.fy.sqlite.model.User;

public class UserDao {

    private SQLiteDatabase database;

    public UserDao(Context context) {
        SQLite sqLite = new SQLite(context);//实例化对象，对象为初始创建的名称
        database = sqLite.getWritableDatabase();//读写操作
    }

    public void addUser(User user) {
        String sql = "insert into user(name, age) values(?, ?)";
        database.execSQL(sql, new Object[]{ user.getName(), user.getAge() });
    }

    public void updateUser(User user) {
        String sql = "update user set name=?, age=? where ID=?";//通过查询编号进行修改
        database.execSQL(sql, new Object[]{ user.getName(), user.getAge(), user.getId() });
    }

    public void delUser(User user) {
        String sql="delete from user where ID=?";
        database.execSQL(sql, new Object[]{ user.getId() });
    }

    public ArrayList<User> queryUser(User user) {
        ArrayList<User> userList = new ArrayList<>();

        String sql = "select * from user";//查询字段名称number
        Cursor cursor = database.rawQuery(sql, null);//获取一个游标
        while(cursor.moveToNext()) {//判断是否可以移动到下一行
            //获取这一行名称的数据,对应的是添加时的字段（列名称）
            int id = cursor.getInt(cursor.getColumnIndexOrThrow("ID"));
            String name = cursor.getString(cursor.getColumnIndexOrThrow("name"));
            int age = cursor.getInt(cursor.getColumnIndexOrThrow("age"));

            User u = new User();
            u.setId(id);
            u.setName(name);
            u.setAge(age);

            userList.add(u);
        }
        return userList;
    }
}
